import {getOpenId} from '.';

export function getSetting(auth,onSuccess,onFail){    //用户授权
  mpvue.getSetting({
    success (res) {
      console.log(res);
      if (res.authSetting[`scope.${auth}`]){
        onSuccess(res);
      }else{
        onFail(res);
      }
    },
    fail(res) {
      console.log(res);
    }
  })
}

export function getUserInfo(onSuccess,onFail) { //用户信息
  // 必须是在用户已经授权的情况下调用
  wx.getUserInfo({
    success: function(res) {
      var userInfo = res.userInfo;
      var nickName = userInfo.nickName;
      var avatarUrl = userInfo.avatarUrl;
      var gender = userInfo.gender;//性别 0：未知、1：男、2：女
      var province = userInfo.province;
      var city = userInfo.city;
      var country = userInfo.country;
      console.log(res);
      if (userInfo) {
        onSuccess(userInfo);
      }else{
        onFail(res);
      }
    },
    fail(res){
      console.log(res);
    },
  })
}

export function setStorageSync(key,data) {
  mpvue.setStorageSync(key,data);
}

export function getStorageSync(key) {
  return mpvue.getStorageSync(key);
}

export function getUserOpenId(callback) {
  mpvue.login({
    success (res) {
      if (res.code){
        const {code} = res;
        console.log('code---'+code);
        getOpenId(code).then(response=>{
          console.log(response);
          const { openid } = response.data.data;
            console.log('openid---'+openid);
            setStorageSync('openId',openid);
            callback && callback(openid);
        }).catch(err=>{
          console.log(err);
        })
      }else{
        console.log(res);
      }
    },
    fail(res) {
      console.log(res);
    }
  })
}

export function showLoading() {
  wx.showLoading({
    title: '加载中...',
  });
}

export function hideLoading() {
  wx.hideLoading();
}

export function showToast(msg) {
  mpvue.showToast({
    title : msg,
    duration : 1000,
  })
}

export function showModal(msg,success) {
  mpvue.showModal({
    title: '提示',
    content: msg,
    success (res) {
      if (res.confirm) {
        success();
      } else if (res.cancel) {
        console.log('用户点击取消')
      }
    }
  })
}
